package com.qf.handler.in;

import com.alibaba.fastjson.JSON;
import com.qf.entity.Msg;
import com.qf.util.ChannelMap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 第一个自定义消息处理器 - 主要功能用于将接受到的json传转换成实体对象，往后传递
 * 修改了BUg
 */
@Component
@ChannelHandler.Sharable
@Order(1000)
public class FirstChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame text) throws Exception {
        //接收到客户端的消息
        String msg = text.text();
        //将json转换成实体类
        Msg msgEntity = JSON.parseObject(msg, Msg.class);
        //直接往后传递
        ctx.fireChannelRead(msgEntity);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有一个客户端连接了服务器");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有一个客户端断开了服务器的连接!");
        ChannelMap.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生通讯异常：");
        cause.printStackTrace();
    }
}
